//
//  XMLoadCacheStatusTool.m
//  XMWeibo
//
//  Created by chi on 14-9-1.
//  Copyright (c) 2014年 xiaoming. All rights reserved.
//

#import "XMLoadCacheStatusTool.h"

#import "FMDB.h"

#import "XMHttpGetStatusParams.h"
#import "XMHttpGetStatusResult.h"
#import "XMStatus.h"

static FMDatabaseQueue *_statusdb;;


@implementation XMLoadCacheStatusTool

/**
 *  获取数据库路径
 */
+ (NSString*)databasePath
{
    static NSString *path;
    if (path == nil) {
        path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        path = [path stringByAppendingPathComponent:@"status.sqlite"];
    }
    
    return path;
}

/**
 *  打开数据库
 */
+ (void)openDatabase
{
    _statusdb = [FMDatabaseQueue databaseQueueWithPath:[self databasePath]];
    
    [_statusdb inDatabase:^(FMDatabase *db) {
        [db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_status(\
        id INTEGER PRIMARY KEY AUTOINCREMENT,\
        idstr TEXT NOT NULL,\
        access_token TEXT NOT NULL,\
         status_data BLOB\
         );"];
    }];
}

/**
 *  关闭数据库
 */
+ (void)closeDatabase
{
    [_statusdb close];
}


+ (void)saveStatusWithParam:(XMHttpGetStatusResult *)result access_token:(NSString *)access_token
{
    // 打开数据库
    [self openDatabase];
    
    [_statusdb inTransaction:^(FMDatabase *db, BOOL *rollback) {
        for (XMStatus *stauts in result.statuses) {
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:stauts];
            
            [db executeUpdate:@"INSERT INTO t_status(idstr, access_token, status_data) VALUES(?, ?, ?);", stauts.idstr, access_token, data];
            
        }
    }];
    
    // 关闭数据库
    [self closeDatabase];
}

/**
 *  通过sqlite加载缓存微博数据
 *
 *  @param params 请求参数
 *
 *  @return 请求结果
 */
+ (XMHttpGetStatusResult *)loadStatusWithParam:(XMHttpGetStatusParams *)params
{
    
    // 打开数据库
    [self openDatabase];

    
    __block XMHttpGetStatusResult *result = [[XMHttpGetStatusResult alloc]init];
    
    [_statusdb inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        FMResultSet *resultSet = nil;
        if (params.since_id) {
            resultSet =  [db executeQuery:@"SELECT status_data FROM t_status WHERE access_token=? AND idstr > ? ORDER BY idstr DESC LIMIT ?", params.access_token, params.since_id, params.count];
        }
        else if (params.max_id) {
            resultSet =  [db executeQuery:@"SELECT status_data FROM t_status WHERE access_token=? AND idstr <= ? ORDER BY idstr DESC LIMIT ?", params.access_token, params.max_id, params.count];
        }
        else {
            resultSet =  [db executeQuery:@"SELECT status_data FROM t_status WHERE access_token=? ORDER BY idstr DESC LIMIT ?;", params.access_token, params.count];
        }
        
        
        if (resultSet.columnCount > 0) {
            NSMutableArray *statsuArray = [NSMutableArray arrayWithCapacity:resultSet.columnCount];
            while (resultSet.next) {
                NSData *data = [resultSet dataForColumn:@"status_data"];
                XMStatus *status = [NSKeyedUnarchiver unarchiveObjectWithData:data];
                [statsuArray addObject:status];
            }
            
            result.statuses = statsuArray;
        }

       
    }];
    
    // 关闭数据库
    [self closeDatabase];
    
    return result;
}








@end
